package com.zhong.scanerdemo;

import java.io.IOException;

import java.util.Vector;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.zhong.scanerdemo.R;
import com.zhong.scanerdemo.camera.CameraManager;
import com.zhong.scanerdemo.decoding.CaptureActivityHandler;
import com.zhong.scanerdemo.decoding.InactivityTimer;
import com.zhong.scanerdemo.interfaces.IHttpRequest;
import com.zhong.scanerdemo.model.UploadResult;
import com.zhong.scanerdemo.network.RequestRunnable;
import com.zhong.scanerdemo.utils.ClientLogUtil;
import com.zhong.scanerdemo.utils.GsonUtil;
import com.zhong.scanerdemo.utils.KeyAndUrl;
import com.zhong.scanerdemo.utils.MD5Util;
import com.zhong.scanerdemo.utils.ScanerParameters;
import com.zhong.scanerdemo.view.ViewfinderView;

public class CaptureActivity extends Activity implements Callback, IHttpRequest {
	private final String TAG = "CaptureActivity";
	private CaptureActivityHandler handler;
	private ViewfinderView viewfinderView;
	private boolean hasSurface;
	private Vector<BarcodeFormat> decodeFormats;
	private String characterSet;
	private InactivityTimer inactivityTimer;
	private MediaPlayer mediaPlayer;
	private boolean playBeep;
	private static final float BEEP_VOLUME = 0.10f;
	private boolean vibrate;
	private Button bt_quit, bt_setting;
	public static SharedPreferences sharedPreferences;
	boolean isUpload;
	private ProgressDialog pDialog;

	private Handler myHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			pDialog.dismiss();

			android.app.AlertDialog.Builder builder = new AlertDialog.Builder(
					CaptureActivity.this);
			builder.setTitle("结果");
			builder.setMessage(msg.getData().getString("msg"));
			builder.setCancelable(false);
			builder.setPositiveButton("继续扫描",
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							onResume();
						}
					});
			builder.create().show();
		}
	};

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_camera);
		// ViewUtil.addTopView(getApplicationContext(), this,
		// R.string.scan_card);
		CameraManager.init(getApplication());
		viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
		bt_quit = (Button) this.findViewById(R.id.btn_cancel_scan);
		bt_setting = (Button) this.findViewById(R.id.btn_setting);
		setListeners();
		hasSurface = false;
		inactivityTimer = new InactivityTimer(this);

		//
		sharedPreferences = this.getSharedPreferences("scaner",
				MODE_WORLD_READABLE);

	}

	private void setListeners() {
		bt_quit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				CaptureActivity.this.finish();
			}
		});

		bt_setting.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(CaptureActivity.this, MainActivity.class);
				startActivity(intent);
			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();
		//
		isUpload = sharedPreferences.getBoolean("isUploadIm", false);

		SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
		SurfaceHolder surfaceHolder = surfaceView.getHolder();
		if (hasSurface) {
			initCamera(surfaceHolder);
		} else {
			surfaceHolder.addCallback(this);
			surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		}
		decodeFormats = null;
		characterSet = null;

		playBeep = true;
		AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
		if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
			playBeep = false;
		}
		initBeepSound();
		vibrate = true;

	}

	@Override
	protected void onPause() {
		super.onPause();
		if (handler != null) {
			handler.quitSynchronously();
			handler = null;
		}
		CameraManager.get().closeDriver();
	}

	@Override
	protected void onDestroy() {
		inactivityTimer.shutdown();
		super.onDestroy();
	}
	
	
	/**
	 * Handler scan result
	 * 
	 * @param result
	 * @param barcode
	 */
	public void handleDecode(Result result, Bitmap barcode) {
		inactivityTimer.onActivity();
		playBeepSoundAndVibrate();
		String resultString = result.getText();

		String dutyOfficer = sharedPreferences.getString("dutyOfficer", "");
		String driver = sharedPreferences.getString("driver", "");
		String carNum = sharedPreferences.getString("carNum", "");
		String startingPoint = sharedPreferences.getString("startingPoint", "");
		String destination = sharedPreferences.getString("destination", "");

		// 新增
		String uid = sharedPreferences.getString("uid", "");
		String pwd = sharedPreferences.getString("pwd", "");
		String source = sharedPreferences.getString("source", "");
		String startDate = sharedPreferences.getString("startDate", "");
		String method = sharedPreferences.getString("method", "");
		String descr = sharedPreferences.getString("descr", "");
		
		// FIXME
		if (resultString.equals("")) {
			Toast.makeText(CaptureActivity.this, "Scan failed!",
					Toast.LENGTH_SHORT).show();
		} else {

			if (isUpload) {
				Log.i("result", "res----------->" + resultString);
				//
				if (handler != null) {
					handler.quitSynchronously();
					handler = null;
				}

				RequestRunnable runnable = new RequestRunnable(ScanerParameters
						.initParameter(uid, pwd, source, startDate, method,
								descr, dutyOfficer, driver, carNum,
								startingPoint, destination, resultString)
						.getNameValuePairs(), CaptureActivity.this,
						KeyAndUrl.REQUEST_URL);
				Thread thread = new Thread(runnable);
				pDialog = new ProgressDialog(CaptureActivity.this);
				pDialog.setMessage("正在 上传，请稍候...");
				pDialog.setCancelable(false);
				pDialog.show();
				thread.start();

			} else {
				Intent resultIntent = new Intent();
				Bundle bundle = new Bundle();
				bundle.putString("result", resultString);
				resultIntent.putExtras(bundle);
				resultIntent.setClass(CaptureActivity.this,
						ResultActivity.class);
				startActivity(resultIntent);
			}

			// this.setResult(RESULT_OK, resultIntent);
		}
		// CaptureActivity.this.finish();
	}

	private void initCamera(SurfaceHolder surfaceHolder) {
		try {
			CameraManager.get().openDriver(surfaceHolder);
		} catch (IOException ioe) {
			return;
		} catch (RuntimeException e) {
			return;
		}
		if (handler == null) {
			handler = new CaptureActivityHandler(this, decodeFormats,
					characterSet);
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {

	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		if (!hasSurface) {
			hasSurface = true;
			initCamera(holder);
		}

	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		hasSurface = false;

	}

	public ViewfinderView getViewfinderView() {
		return viewfinderView;
	}

	public Handler getHandler() {
		return handler;
	}

	public void drawViewfinder() {
		viewfinderView.drawViewfinder();

	}

	private void initBeepSound() {
		if (playBeep && mediaPlayer == null) {
			// The volume on STREAM_SYSTEM is not adjustable, and users found it
			// too loud,
			// so we now play on the music stream.
			setVolumeControlStream(AudioManager.STREAM_MUSIC);
			mediaPlayer = new MediaPlayer();
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mediaPlayer.setOnCompletionListener(beepListener);

			AssetFileDescriptor file = getResources().openRawResourceFd(
					R.raw.beep);
			try {
				mediaPlayer.setDataSource(file.getFileDescriptor(),
						file.getStartOffset(), file.getLength());
				file.close();
				mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
				mediaPlayer.prepare();
			} catch (IOException e) {
				mediaPlayer = null;
			}
		}
	}

	private static final long VIBRATE_DURATION = 200L;

	private void playBeepSoundAndVibrate() {
		if (playBeep && mediaPlayer != null) {
			mediaPlayer.start();
		}
		if (vibrate) {
			Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
			vibrator.vibrate(VIBRATE_DURATION);
		}
	}

	/**
	 * When the beep has finished playing, rewind to queue up another one.
	 */
	private final OnCompletionListener beepListener = new OnCompletionListener() {
		public void onCompletion(MediaPlayer mediaPlayer) {
			mediaPlayer.seekTo(0);
		}
	};

	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		CaptureActivity.this.finish();
	}

	@Override
	public void refresh(String result) {
		// TODO Auto-generated method stub
		ClientLogUtil.i(TAG, "result----------->" + result);
		Message msg = myHandler.obtainMessage();
		Bundle bundle = new Bundle();
		UploadResult uploadResult=GsonUtil.useGson(result);
		if(uploadResult!=null){
			bundle.putString("state", uploadResult.getState());
			bundle.putString("msg", uploadResult.getMsg());
			ClientLogUtil.i(TAG,
					"josn result----------->" + uploadResult.toString());
		}else {
			bundle.putString("state", "");
			bundle.putString("msg", "网络出错");
		}
		msg.setData(bundle);
		myHandler.sendMessage(msg);
	}

}